/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-08 15:07:43
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.contractor.BpContractorBean;
import com.joysuch.wwyt.bp.bean.contractor.BpContractorEvaluationBean;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorEvaluation;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpContractorEvaluationDao;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.service.BpContractorEvaluationService;
import com.joysuch.wwyt.bp.service.BpContractorService;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class BpContractorEvaluationServiceImpl implements BpContractorEvaluationService {

    @Autowired
    private BpContractorEvaluationDao dao;
    @Autowired
    private BpDepartService departService;
    @Autowired
    private BpContractorService contractorService;
    @Autowired
    private BpDepartDao bpDepartDao;

    @Override
    public ResultBean page(Pageable page, Long contractorId) {
        Assert.notNull(contractorId, "contractorId cannot be null");
        page = PageDataUtils.addOrderByDesc(page, "id");
        Specification<BpContractorEvaluation> specification = (Root<BpContractorEvaluation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("contractorId"), contractorId));
            predicates.add(cb.equal(root.get("state"), DataStateTypes.EFFECTIVE.getState()));
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        Page<BpContractorEvaluation> list = dao.findAll(specification, page);
        for (BpContractorEvaluation evaluation : list) {
            if (evaluation.getInspectionDepartId() != null) {
                Optional<BpDepart> obd = bpDepartDao.findById(evaluation.getInspectionDepartId());
                if (obd.isPresent()) {
                    evaluation.setInspectionDepartName(obd.get().getName());
                }
            }
        }
        return ResultBean.pageData(list.getContent(), list.getTotalElements());
    }

    @Override
    public ResultBean getById(Long id) {
        Assert.notNull(id, "id cannot be null");
        //查询违章记录表
        BpContractorEvaluation entity = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        BpContractorEvaluationBean bean = new BpContractorEvaluationBean();
        BeanUtils.copyProperties(entity, bean);
        return ResultBean.success(bean);
    }

    @Override
    public ResultBean save(BpContractorEvaluationBean bean) {
        Long id = bean.getId();
        BpContractorEvaluation entity;
        if (id == null) {
            log.info("开始新增承包商判定");
            entity = new BpContractorEvaluation();
            //保存部门
            if (bean.getInspectionDepartId() != null) {
                BpDepart byId = departService.findById(bean.getInspectionDepartId());
                bean.setInspectionDepartName(byId.getName());
            }
            entity.setState(DataStateTypes.EFFECTIVE.getState());

        } else {
            log.info("开始修改承包商判定");
            entity = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("系统繁忙"));
            if (DataStateTypes.UN_EFFECTIVE.getState().equals(entity.getState())) {
                return ResultBean.fail(101, "此数据已作废");
            }
        }
        //查询最后一次
        BpContractorEvaluation evaluation = dao.findBycAndContractorId(bean.getContractorId());
        BeanUtils.copyProperties(bean, entity, "code", "state");
        if (evaluation==null||(evaluation.getInspectionDate()!=null&&evaluation.getInspectionDate().isBefore(entity.getInspectionDate()))||
                (bean.getId()!=null&&evaluation.getId().equals(bean.getId()))|| evaluation.getInspectionDate().equals(bean.getInspectionDate())) {
            //变更承包商类型
            ResultBean resultBean = contractorService.getById(bean.getContractorId());
            BpContractorBean contractorBean = (BpContractorBean) resultBean.getData();
            if ("不合格承包商".equals(bean.getInspectionResults())) {
                contractorBean.setContractorType("不合格承包商");
            } else if ("合格承包商".equals(bean.getInspectionResults())) {
                contractorBean.setContractorType("合格承包商");
            }else {
                contractorBean.setContractorType("准承包商");
            }
            contractorService.save(contractorBean);
        }
        dao.save(entity);
        return ResultBean.defaultSuccessResult();
    }


    @Override
    @Transactional
    public ResultBean delete(Long id) {
        Assert.notNull(id, "id cannot be null");
        BpContractorEvaluation entity = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        dao.delete(entity);
        BpContractorEvaluation evaluation = dao.findBycAndContractorId(entity.getContractorId());
        if (evaluation!=null){
            ResultBean resultBean = contractorService.getById(entity.getContractorId());
            BpContractorBean contractorBean = (BpContractorBean) resultBean.getData();
            if ("不合格承包商".equals(evaluation.getInspectionResults())) {
                contractorBean.setContractorType("不合格承包商");
            } else if ("合格承包商".equals(evaluation.getInspectionResults())) {
                contractorBean.setContractorType("合格承包商");
            }else {
                contractorBean.setContractorType("准承包商");
            }
            contractorService.save(contractorBean);
        }
        return ResultBean.defaultSuccessResult();
    }
}
